package logic

import (
	"context"
	"encoding/json"

	"googee/common/errorx"
	"googee/service/inbox/api/internal/svc"
	"googee/service/inbox/api/internal/types"
	"googee/service/inbox/rpc/types/inbox"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type GetmessageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetmessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetmessageLogic {
	return &GetmessageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetmessageLogic) Getmessage(req *types.IdReq) (resp *types.MessageReply, err error) {
	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	resp = &types.MessageReply{}

	msg, err := l.svcCtx.Inbox.GetMessage(l.ctx, &inbox.IdRequest{
		UserId: id,
		Id:     req.Id,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.NotFound {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 1)
			} else if st.Code() == codes.Internal {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			} else {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	copier.Copy(&resp.Data, msg)

	return
}
